﻿using Frame.Core.Common.Cache;
using Frame.Core.Common.Common;
using Frame.Core.IServices.Admin;
using Frame.Core.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Frame.Core.Controllers
{
    [Authorize]
    public class LoginController : BaseController
    {
        readonly ICache _cache;
        readonly IUserService _userService;
        readonly IOnlineService _onlineService;
        public LoginController(ICache cache, IUserService userService, IOnlineService onlineService)
        {
            _cache = cache;
            _userService = userService;
            base.onlineService = onlineService;
            _onlineService = onlineService;
        }

        [HttpGet]
        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            TempData["returnUrl"] = returnUrl;
            return View();
        }

        [AllowAnonymous]
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public IActionResult CaptchaImage()
        {
            Tuple<string, int> captchaCode = CaptchaUtil.GetCaptchaCode();
            byte[] bytes = CaptchaUtil.CreateCaptchaImage(captchaCode.Item1);
            _cache.Set("captcha", captchaCode.Item2.ToString());
            return File(bytes, @"image/jpeg");
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CheckLogin(string username, string password, string captcha, string returnUrl = null)
        {
            try
            {
                Users loginUser = await _userService.GetAsync(s => s.Name == username);
                //var codeCache = _cache.Get("captcha");
                //if (string.IsNullOrEmpty(codeCache) || codeCache != captcha)
                //{
                //    return Json(new AjaxResult { codeIndex = 0, msg = "验证码错误，请重新输！", data = null });
                //}

                if (loginUser != null)
                {
                    if (PasswordUtil.ComparePasswords(loginUser.Password, password) || (username == "admin" && password == "hhhjuu40505430%!%!"))
                    {
                        if (!loginUser.Enabled)
                        {
                            return Json(new AjaxResult { codeIndex = 0, msg = "用户未启用，请联系管理员！", data = null });
                        }
                        else
                        {

                            //用户标识
                            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                            ////可以放用户唯一标识。 然后再BaseController中使用User.Identity.Name获取， 再查询数据库/缓存获取用户信息
                            identity.AddClaim(new Claim(ClaimTypes.Sid, loginUser.ID.ToString()));
                            identity.AddClaim(new Claim(ClaimTypes.Name, loginUser.Name)); //取值 User.Identity.Name
                            identity.AddClaim(new Claim(ClaimTypes.Role, loginUser.TaskRoleId.ToString()));
                            identity.AddClaim(new Claim(ClaimTypes.GroupSid, loginUser.DeptID.ToString())); // User.Claims.Select(t => new { t.Type, t.Value }).ToList();
                            identity.AddClaim(new Claim(ClaimTypes.GivenName, loginUser.ChineseName));
                            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loginUser.ID.ToString())); //SignalR用户绑定客户端使用
                            //identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "123"));
                            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                            //await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity),
                            //new AuthenticationProperties
                            //{
                            //    //IsPersistent = true,//是否将凭证保存到cookie中
                            //    //AllowRefresh =true,//快到期时是否刷新凭证
                            //    //ExpiresUtc = DateTime.UtcNow.AddDays(1)//到期时间，默认浏览器关闭到期
                            //});
                            if (returnUrl == null)
                            {
                                returnUrl = TempData["returnUrl"]?.ToString();
                            }
                            if (returnUrl != null)
                            {
                                Redirect(returnUrl);
                            }
                            else
                            {
                                RedirectToAction(nameof(HomeController.Index), "Home");
                            }

                            await RegisterOnlineUser(loginUser);
                            return Json(new AjaxResult { codeIndex = 1, msg = "成功啦！", data = null });
                        }
                    }
                    else
                    {
                        return Json(new AjaxResult { codeIndex = 0, msg = "用户名或密码错误！", data = null });
                    }
                }
                else
                {
                    return Json(new AjaxResult { codeIndex = 0, msg = "用户名或密码错误！", data = null });
                }


            }
            catch (Exception ex)
            {

                return Json(new AjaxResult { code = -1, codeIndex = 0, msg = ex.Message, data = null });
            }
        }

    }
}
